package com.finstone.data.spider.eshop.pipeline;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.AbstractSqlParameterSource;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import us.codecraft.webmagic.pipeline.Pipeline;

public abstract class BasePipeline implements Pipeline {

	@Autowired
	protected JdbcTemplate jdbcTempate;

	protected static BeanPropertySqlParameterSource paramBeanMapper(Object object) {
		return new BeanPropertySqlParameterSource(object);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected static MapSqlParameterSource paramMapMapper(Map object) {
		return new MapSqlParameterSource(object);
	}

	@SuppressWarnings("rawtypes")
	public static AbstractSqlParameterSource paramMapper(Object object) {
		if (object instanceof Map) {
			return paramMapMapper((Map) object);
		} else {
			return paramBeanMapper(object);
		}
	}

	@SuppressWarnings("rawtypes")
	public static AbstractSqlParameterSource[] paramMapper(List list) {
		if (list != null) {
			AbstractSqlParameterSource[] sources = new AbstractSqlParameterSource[list.size()];
			for (int i = 0; i < list.size(); i++) {
				Object item = list.get(i);
				sources[i] = paramMapper(item);
			}
			return sources;
		}
		return null;
	}

	public static <T> ParameterizedBeanPropertyRowMapper<T> resultBeanMapper(Class<T> clazz) {
		return ParameterizedBeanPropertyRowMapper.newInstance(clazz);
	}

	public JdbcTemplate getJdbcTempate() {
		return jdbcTempate;
	}

	public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
		return new NamedParameterJdbcTemplate(getJdbcTempate());
	}

	public void setJdbcTempate(JdbcTemplate jdbcTempate) {
		this.jdbcTempate = jdbcTempate;
	}
}
